function binaryToStrings(binaryData) {
    var decodedString = atob(binaryData);
    return decodedString.split(".......");
}
// function binaryToStrings(binaryData) {
//     var decoder = new TextDecoder("gbk");
//     var decodedString = decoder.decode(binaryData);
//     return decodedString.split(".");
// }

function binaryToStrings1(binaryData) {
    var base64Data = btoa(String.fromCharCode.apply(null, binaryData));
    var decodedString = atob(base64Data);
    return decodedString.split(".");
}
function getRandomLowercaseLetter() {
    const alphabet = 'abcdefghijklmnopqrstuvwxyz';
    let result = '';
    for (let i = 0; i < 1; i++) {
        result += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
    }
    return result;
}
var key=getRandomLowercaseLetter();
// 当页面加载完成后执行
$(document).ready(function() {
    console.log(key);
    // 点击按钮时发送 Ajax 请求

    $.ajax({
        url: 'http://localhost:80/Index?key='+key,  // 后端提供的 API 地址
        method: 'POST',
        success: function(response) {
            var data1 = JSON.parse(response);
            console.log(data1);
            for (let i=0;i<data1.word.length;i++){
                displayWord(data1.word[i]);
            }
            // displayWord(data1.word);
        },
        error: function(xhr, status, error) {
            console.error('Error fetching word:', error);
        }
    });
    // 显示单词及其相关信息

});
function displayWord(wordData) {
    let number = Math.floor(Math.random() * binaryToStrings(wordData.information).length + 1);
    var wordHtml = '<div class="newElement">';
    wordHtml += '<h2>' + wordData.words + '</h2><br>';
    wordHtml += '<button onclick="playSound(\'' + wordData.explain + '\')">' + wordData.explain + '</button><br>';
    wordHtml += '<button onclick="playAudio(\'' + wordData.audio + '\')">播放单词</button><br>';
    wordHtml += '<button onclick="playSound(\'' + binaryToStrings(wordData.information).at(number) + '\')">' + binaryToStrings(wordData.information).at(number) + '</button><br>';
    wordHtml += '</div>';
    document.getElementById('wordContainer').insertAdjacentHTML('beforeend', wordHtml);
}
function click(wordData){
    let number = Math.floor(Math.random() * binaryToStrings(wordData.information).length  + 1);
    console.log( binaryToStrings(wordData.information).at(number));
    playSound(binaryToStrings(wordData.information).at(number));
}
function playAudio(audioData) {
    // 将音频数据转换为二进制数据
    var binaryAudioData = Uint8Array.from(atob(audioData), c => c.charCodeAt(0));
    var blob = new Blob([binaryAudioData], { type: 'audio/mp3' });
    // 创建二进制数据的URL链接
    var audioURL = URL.createObjectURL(blob);
    // 创建音频对象并播放
    var audio = new Audio(audioURL);
    audio.play();
}
function playSound(data){
    var message = new SpeechSynthesisUtterance();
    // 设置要转换为语音的文本内容
    message.text = data;
    // 使用中文（中国）作为语音合成的语言
    message.lang = "zh-CN";
    // 使用浏览器的语音合成服务将文本转换为语音并播放
    window.speechSynthesis.speak(message);
}
function inputChanged() {
    var inputValue = document.getElementById("search-box").value;
    // console.log("输入框的值已更改：" + inputValue);
    key=inputValue;
    $.ajax({
        url: 'http://localhost:80/Home?key='+key,  // 后端提供的 API 地址
        method: 'POST',
        success: function(response) {
            var data1 = JSON.parse(response);
            let element=document.getElementById("wordContainer");
            element.innerHTML='';
            console.log(data1);
            for (let i=0;i<data1.word.length;i++){
                // console.log(data1.word[i]);
                displayWord(data1.word[i]);
            }
        },
        error: function(xhr, status, error) {
            console.error('Error fetching word:', error);
        }
    });
}
function checkEnterKey(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        document.getElementById('earch-button').click();
    }
}
function Quary(key){
    var inputValue = document.getElementById("search-box").value;
    // console.log("输入框的值已更改：" + inputValue);
    key=inputValue;
    $.ajax({
        url: 'http://localhost:80/Home1?key='+key,  // 后端提供的 API 地址
        method: 'POST',
        success: function(response) {
            var data1 = JSON.parse(response);
            let element=document.getElementById("wordContainer");
            element.innerHTML='';
            for (let i=0;i<data1.word.length;i++){
                // console.log(data1.word[i]);
                displayWord(data1.word[i]);
            }
        },
        error: function(xhr, status, error) {
            console.error('Error fetching word:', error);
        }
    });

}
document.addEventListener('keydown', function(event) {
    if (event.key === 'Enter') {
        search();
    }
});
function search(){
    var inputValue = document.getElementById("search-box").value;
    let elementById = document.getElementById("wordContainer");
    elementById.innerHTML='';
    $.ajax({
        url: 'http://localhost:80/Home?key='+inputValue,  // 后端提供的 API 地址
        method: 'POST',
        success: function(response) {
            var data1 = JSON.parse(response);
            let element=document.getElementById("wordContainer");
            element.innerHTML='';
            for (let i=0;i<data1.word.length;i++){
                // console.log(data1.word[i]);
                displayWord(data1.word[i]);
            }
        },
        error: function(xhr, status, error) {
            console.error('Error fetching word:', error);
        }
    });


}
function search(){
    var inputValue = document.getElementById("search-box").value;
    let elementById = document.getElementById("wordContainer");
    elementById.innerHTML='';
    $.ajax({
        url: 'http://localhost:80/Home?key='+inputValue,  // 后端提供的 API 地址
        method: 'POST',
        success: function(response) {
            var data1 = JSON.parse(response);
            console.log(data1);
            let element=document.getElementById("wordContainer");
            element.innerHTML='';
            for (let i=0;i<data1.word.length;i++){
                displayWord(data1.word[i]);
            }
        },
        error: function(xhr, status, error) {
            console.error('Error fetching word:', error);
        }
    });
}

